package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.BaseContext;
import com.itheima.entity.*;
import com.itheima.mapper.*;
import com.itheima.service.OrdersService;
import com.itheima.vo.OrderVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrdersServiceImpl implements OrdersService {

    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddressMapper addressMapper;
    @Autowired
    private ShoppingCartMapper shoppingCarMapper;
    @Autowired
    private UserMapper userMapper;
    @Override
    public Map<String, Object> historicalOrder(Integer page, Integer pageSize) {
        //校验和判断
        if (page < 1) {
            page = 1;
        }
        if (pageSize < 1) {
            pageSize = 5;
        }
        //创建分页条件
        //orderTime status  orderDetails(name number) sumNum amount
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        //根据userid 查询用户的所有订单
        LambdaQueryWrapper<Orders> ordersQueryWrapper = new LambdaQueryWrapper<>();
        Long userId = BaseContext.getUserId();
        ordersQueryWrapper.eq(userId!= null,Orders::getUserId,userId);

        Page<Orders> ordersPages = ordersMapper.selectPage(ordersPage, ordersQueryWrapper);
        if (ordersPages == null){
            return null;
        }
        List<Orders> ordersList = ordersPages.getRecords();
        if (ordersList == null || ordersList.size() < 1){
            return null;
        }
        Long total = ordersPage.getTotal();
        Long pages = (total/pageSize)+1;
        LambdaQueryWrapper<OrderDetail> orderDetailQueryWrapper = null;
        ArrayList<OrderVO> orderVOList = new ArrayList<>();
        //根据用户id 查询订单详情
        for (Orders order : ordersList) {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(order,orderVO);

            orderDetailQueryWrapper = new LambdaQueryWrapper<>();
            orderDetailQueryWrapper.eq(OrderDetail::getOrderId,order.getId());
            List<OrderDetail> orderDetails = orderDetailMapper.selectList(orderDetailQueryWrapper);
            orderVO.setOrderDetails(orderDetails);
            orderVOList.add(orderVO);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("pages",pages);
        map.put("orderVOList",orderVOList);
        return map;
    }
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public int submitOrder(Orders orders) {
        int row = 0;
        //1.校验参数  地址ID、支付方式
        if(orders == null){
            return row;
        }
        //2.生成订单----新增一条订单数据、新增一条或多条订单明细
        //2.1 新增一条订单数据，分析需要补全数据：user_id、order_time、amount（计算）、phone、address、user_name、consignee
        Long userId = BaseContext.getUserId();
        if(userId == null){
            return row;
        }
        //2.1.1 获取购物车详情----1.计算订单总金额 2.添加订单详情
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId,userId);
        //根据时间降序排序
        wrapper.orderByDesc(ShoppingCart::getCreateTime);
        //获取购物车列表数据
        List<ShoppingCart> shoppingCartList = shoppingCarMapper.selectList(wrapper);
        if(shoppingCartList == null || shoppingCartList.size() ==0){
            return row;
        }
        int amount = 0;
        for (ShoppingCart shoppingCart : shoppingCartList) {
            Integer number = shoppingCart.getNumber();
            BigDecimal cartAmount = shoppingCart.getAmount();
            amount = amount+number*cartAmount.intValue();
        }
        //2.1.2 获取地址信息----补全订单表中地址相关数据 phone、address、consignee
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressMapper.selectById(addressBookId);
        String phone = addressBook.getPhone();
        String detail = addressBook.getDetail();
        String consignee = addressBook.getConsignee();
        //2.1.3 获取用户信息----补全订单表中用户名称 user_name
        User user = userMapper.selectById(userId);
        String name = user.getName();
        //补全数据
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setAmount(new BigDecimal(amount));
        orders.setPhone(phone);
        orders.setAddress(detail);
        orders.setUserName(name);
        orders.setConsignee(consignee);
        row = ordersMapper.insert(orders);
        if(row<1){
            return row;
        }
        //2.2 新增一条或多条订单明细 name、image、order_id、dish_id、setmeal_id、dish_flavor、number、amount
        for (ShoppingCart shoppingCart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart,orderDetail);
            orderDetail.setId(null);
            orderDetail.setOrderId(orders.getId());
            orderDetailMapper.insert(orderDetail);
        }
        //3.情况当前用户购物车-----根据UserID删除购物车数据
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,userId);
        shoppingCarMapper.delete(queryWrapper);
        return row;
    }
}
